package com.hj.springframework3.with.tx;

import com.hj.springframework3.JdbcTestBase;
import com.hj.springframework3.annotation.Autowired;
import com.hj.springframework3.annotation.Component;
import com.hj.springframework3.annotation.Transactional;
import com.hj.springframework3.jdbc.JdbcTemplate;

/**
 * @Author : hujing
 * @Date: 2025/7/14 10:57
 * @Description:
 */
@Component
@Transactional
public class UserService {
    @Autowired
    AddressService addressService;
    @Autowired
    JdbcTemplate jdbcTemplate;

    // 创建用户
    public User createUser(String name, int age) {
        Number id = jdbcTemplate.updateAndReturnGeneratedKey(JdbcTestBase.INSERT_USER, name, age);
        User user = new User();
        user.id = id.intValue();
        user.name = name;
        user.theAge = age;
        return user;
    }

    // 根据用户id获取用户
    public User getUser(int userId) {
        return jdbcTemplate.queryForObject(JdbcTestBase.SELECT_USER, User.class, userId);
    }
    
    // 更新用户
    public void updateUser(User user){
        jdbcTemplate.update(JdbcTestBase.UPDATE_USER,user.id,user.name,user.theAge);
    }
    
    // 根据用户id删除用户,删除地址
    public void deleteUser(User user){
        jdbcTemplate.update(JdbcTestBase.DELETE_USER,user.id);
        addressService.deleteAddress(user.id);
    }
}
